﻿using System;
using System.Text;
using System.Web.Security;

namespace AnOtherBlog.AJAX.SetUp.MRPP
{
	public partial class CreateAdminUser : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}
		protected void LinkButton1_Click(object sender, EventArgs e)
		{
			CreateAdmin();
		}

		/// <summary>
		/// Esto sirve para crear el grupo/rol Administrators y el usuario admin con password admin
		/// </summary>
		private void CreateAdmin()
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine("Setup Membership, Role and Profile");

			string userName;
			string roleName;
			MembershipUserCollection membershipUserCollection;

			Membership.ApplicationName = "AnOtherBlog";

			// Create Role: Administrators
			roleName = "Administrators";

			if (!Roles.RoleExists(roleName))
			{
				Roles.CreateRole(roleName);
				sb.AppendLine("Added Role " + roleName);
			}
			else
			{
				sb.AppendLine("Role " + roleName + " already exist");
			}

			// Create User: admin Password: admin
			userName = "admin";

			membershipUserCollection = Membership.FindUsersByName(userName);
			if (membershipUserCollection.Count == 0)
			{
				MembershipCreateStatus userStatus = new MembershipCreateStatus();
				Membership.CreateUser(userName, userName, userName + @"@somedomain.com", "ask", "answer", true, out userStatus);
				if (userStatus == MembershipCreateStatus.Success)
				{
					Roles.AddUserToRole(userName, roleName);
					if (Roles.IsUserInRole(userName, roleName))
					{
						sb.AppendLine("User: " + userName + " added to Role: " + roleName);
					}
					else
					{
						sb.AppendLine("Can not add user: " + userName + " to Role: " + roleName);
					}
				}
				else
				{
					sb.AppendLine("Can not create user: " + userName);
				}
			}
			else
			{
				sb.AppendLine("User: " + userName + " already exist");
				if (Roles.IsUserInRole(userName, roleName))
				{
					sb.AppendLine("User: " + userName + " already in Role: " + roleName);
				}
				else
				{
					Roles.AddUserToRole(userName, roleName);
					if (Roles.IsUserInRole(userName, roleName))
					{
						sb.AppendLine("User: " + userName + " added to Role: " + roleName);
					}
					else
					{
						sb.AppendLine("Can not add user: " + userName + " to Role: " + roleName);
					}
				}
			}

			TextBox1.Text = sb.ToString();
		}
	}
}
